// API 基础URL
const API_URL = 'http://localhost:3000/api/todos';

// DOM 元素
const todoInput = document.getElementById('todoInput');
const addBtn = document.getElementById('addBtn');
const todoList = document.getElementById('todoList');
const totalCount = document.getElementById('totalCount');
const completedCount = document.getElementById('completedCount');
const pendingCount = document.getElementById('pendingCount');
const emptyState = document.getElementById('emptyState');

// 状态管理
let todos = [];

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadTodos();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    addBtn.addEventListener('click', addTodo);
    todoInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addTodo();
    });
}

// 加载待办事项
async function loadTodos() {
    try {
        const response = await fetch(API_URL);
        if (!response.ok) throw new Error('加载失败');
        
        todos = await response.json();
        renderTodos();
    } catch (error) {
        console.error('加载待办事项失败:', error);
        showError('加载待办事项失败，请刷新页面重试');
    }
}

// 添加新的待办事项
async function addTodo() {
    const text = todoInput.value.trim();
    if (!text) {
        alert('请输入待办事项内容');
        return;
    }

    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text })
        });

        if (!response.ok) throw new Error('添加失败');
        
        const newTodo = await response.json();
        todos.push(newTodo);
        todoInput.value = '';
        renderTodos();
    } catch (error) {
        console.error('添加待办事项失败:', error);
        alert('添加失败，请重试');
    }
}

// 更新待办事项状态
async function toggleTodo(id) {
    const todo = todos.find(t => t.id === id);
    if (!todo) return;

    try {
        const response = await fetch(`${API_URL}/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ completed: !todo.completed })
        });

        if (!response.ok) throw new Error('更新失败');
        
        todo.completed = !todo.completed;
        renderTodos();
    } catch (error) {
        console.error('更新状态失败:', error);
        alert('更新失败，请重试');
    }
}

// 删除待办事项
async function deleteTodo(id) {
    if (!confirm('确定要删除这个待办事项吗？')) return;

    try {
        const response = await fetch(`${API_URL}/${id}`, {
            method: 'DELETE'
        });

        if (!response.ok) throw new Error('删除失败');
        
        todos = todos.filter(t => t.id !== id);
        renderTodos();
    } catch (error) {
        console.error('删除待办事项失败:', error);
        alert('删除失败，请重试');
    }
}

// 渲染待办事项列表
function renderTodos() {
    updateStats();
    
    if (todos.length === 0) {
        todoList.innerHTML = '';
        emptyState.style.display = 'block';
        return;
    }

    emptyState.style.display = 'none';
    todoList.innerHTML = todos.map(todo => `
        <li class="todo-item">
            <input 
                type="checkbox" 
                class="todo-checkbox" 
                ${todo.completed ? 'checked' : ''}
                onchange="toggleTodo(${todo.id})"
            >
            <span class="todo-text ${todo.completed ? 'completed' : ''}" onclick="toggleTodo(${todo.id})">
                ${escapeHtml(todo.text)}
            </span>
            <button class="todo-delete" onclick="deleteTodo(${todo.id})">
                <i class="fas fa-trash"></i>
            </button>
        </li>
    `).join('');
}

// 更新统计信息
function updateStats() {
    const total = todos.length;
    const completed = todos.filter(t => t.completed).length;
    const pending = total - completed;

    totalCount.textContent = total;
    completedCount.textContent = completed;
    pendingCount.textContent = pending;
}

// HTML转义函数，防止XSS攻击
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示错误信息
function showError(message) {
    todoList.innerHTML = `<div class="error">${message}</div>`;
    emptyState.style.display = 'none';
}
